import config from "../config"

const app = getApp();
const request = (url, options, showLoading) => {
  return new Promise((resolve, reject) => {
    if (showLoading) {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: `${config.baseurl}/${url}`,
      method: options.method,
      data: options.data,
      header: {
        'content-type': options.isObjType ?
          'application/json': 'application/x-www-form-urlencoded',
        // 添加cookie认证信息
        'cookie': app.globalData.userCookie?app.globalData.userCookie:'',
      },
      success(response) {
        if (options.data.isLogin) {
          // 如果是登录接口，需要保存服务器返回的token信息
          response.cookies?.find((cookieItem) => {
            if (cookieItem.startsWith("MUSIC_U=")) {
              // 缓存cookie到本地
              app.globalData.userCookie = cookieItem;
              // 缓存数据到本地
              wx.setStorageSync(config.STORE_USER_COOKIE_KEY, cookieItem);
              return true;
            }
          })
        }
        resolve(response.data)
      },
      fail(error) {
        console.log(error);
        reject(error.data)
      },
      complete: () => {
        if (showLoading) {
          wx.hideLoading();
        }
      }
    })
  })
}

const get = (url, options = {}, showLoading = false) => {
  return request(url, {
    method: 'GET',
    data: options,
  },
    showLoading);
}

//post对象
const postObjct = (url, options, showLoading = false) => {
  return request(url, {
    method: 'POST',
    data: options,
    isObjType: true,
  },
    showLoading)
}
//post参数
const post = (url, options, showLoading = false) => {
  return request(url, {
    method: 'POST',
    data: options,
    isObjType: false,
  },
    showLoading);
}

const put = (url, options, showLoading = false) => {
  return request(url, {
    method: 'PUT',
    data: options,
  },
    showLoading);
}

// 不能声明DELETE（关键字）
const remove = (url, options, showLoading = false) => {
  return request(url, {
    method: 'DELETE',
    data: options,
  },
    showLoading)
}

module.exports = {
  get,
  post,
  postObjct,
  put,
  remove,
}